package cn.zgz.validCode;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sun.java2d.loops.DrawLine;

public class RandomValidateCode {
	public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";
	private Random random = new Random();
	private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	private int width = 80;
	private int height = 26;
	private int lineSize = 100;
	private int stringNum = 4;
	private Font getFont() {
		return new Font("Times new Roman",Font.ROMAN_BASELINE,18);
	}
	private Color getRandColor() {
		int r = random.nextInt(256);
		int g = random.nextInt(256);
		int b = random.nextInt(256);
		return new Color(r,g,b);
	}
	public void getRandcode(HttpServletRequest request,HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.fillRect(0, 0, width, height);
		g.setColor(getRandColor());
		for(int i = 0;i<lineSize;i++) {
			drawLine(g);
		}
		String randomString = "";
		for(int i = 0;i<=stringNum;i++) {
			randomString = drawString(g,randomString,i);
		}
		session.removeAttribute(RANDOMCODEKEY);
		session.setAttribute(RANDOMCODEKEY, randomString);
		g.dispose();
		ImageIO.write(image,"PNG",response.getOutputStream());
	}
	private String drawString(Graphics g, String randomString, int i) {
		g.setFont(getFont());
		g.setColor(new Color(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
		g.translate(random.nextInt(3), random.nextInt(3));
		String rand = String.valueOf(getRandomString(random.nextInt(randString.length())));
		randomString += rand;
		g.drawString(rand, 13 * i, 16);
		return randomString;
	}
	private String getRandomString(int num) {
		return String.valueOf(randString.charAt(num));
	}
	private void drawLine(Graphics g) {
		int x = random.nextInt(width);
		int y = random.nextInt(height);
		int xl = random.nextInt(13);
		int yl = random.nextInt(15);
		g.drawLine(x, y, x+xl, y+yl);
	}
}
